﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreeDream.Common
{
    public class Base64Helper
    {

        #region 文件转Base64
        /// <summary>
        /// 文件转Base64
        /// </summary>
        /// <param name="fileName">文件全路径：fileName</param>
        /// <returns></returns>
        public static string DocumentToBase64Str(string fileName)
        {
            FileStream filestream = new FileStream(fileName, FileMode.Open);

            byte[] bt = new byte[filestream.Length];
            //调用read读取方法
            filestream.Read(bt, 0, bt.Length);
            string base64Str = Convert.ToBase64String(bt);
            filestream.Close();
            return base64Str;
        }
        #endregion

        #region Base64转文件
        /// <summary>
        /// Base64转文件
        /// </summary>
        /// <param name="Base64String"></param>
        /// <param name="FileNamePath">文件保存路径</param>
        public static bool SaveDocument(string Base64String, string FileNamePath)
        {
            try
            {
                //判断文件是否存在，存在先删了
                if (System.IO.File.Exists(FileNamePath))
                {
                    System.IO.File.Delete(FileNamePath);
                }
                //注意：文件直接转base64前面会带有“data:application/pdf;base64,”前缀，需要去掉。
                var TargetStr = "base64,";
                var Sindex = Base64String.IndexOf(TargetStr);
                if (Sindex != -1)
                {
                    var SindexOffset = TargetStr.Length;
                    Sindex += SindexOffset;
                    Base64String = Base64String.Substring(Sindex);
                }

                byte[] DocBytes = Convert.FromBase64String(Base64String);
                //文件流创建文件内容
                FileStream fs = new FileStream(FileNamePath, FileMode.OpenOrCreate);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(DocBytes, 0, DocBytes.Length);
                bw.Close();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion
    }
}
